<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\api\model\PlatformLog;
use app\common\controller\Backend;
use app\common\model\Config;
use EasyWeChat\Factory;
use think\facade\Db;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    protected $relationSearch = true;
    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
        $venueList = \app\admin\model\Venue::getVenueList(['is_delete' => 1]);
        $this->view->assign('venueList', $venueList);
        $this->assignconfig('venueList', $venueList);
        $statusList = \app\admin\model\Order::fetchStatus();
        $this->view->assign('statusList', $statusList);
        $this->assignconfig('statusList', $statusList);
        $useStatusList = \app\admin\model\Order::fetchUseStatus();
        $this->view->assign('useStatusList', $useStatusList);
        $this->assignconfig('useStatusList', $useStatusList);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看.
     */
    public function index()
    {
        $user_id = request()->param('user_id');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $builder = $this->model->withJoin(['user'])->where($where)->where('is_delete', 1);
            if($user_id){
                $builder->where('user_id', $user_id);
            }
            $total = $builder
                ->order($sort, $order)
                ->count();
            $list  = $builder
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = ['total' => $total, 'rows' => $list];
            foreach ($list as $key => $value){
                $time_list = json_decode($value['time_list'], true);
                $site_id_list = array_column($time_list, 'site_id');
                $site_list = \app\admin\model\Site::where('id', 'in', $site_id_list)->column('site_name', 'id');
                $time_data = "";
                foreach ($time_list as $k => $val){
                    $time_data .= $site_list[$val['site_id']] . "：" . $val['time'] . "，";
                }
                $list[$key]['time_list'] = $time_data;
            }
            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $row = $this->model
            ->with(['users', 'venues'])
            ->field('out_trade_no,user_id,venue_id,date,time_list,all_money,status,use_status,createtime,transaction_id,time_end,total_fee,out_refund_no,refund_id,refund_time,refund_money,pay_type')
            ->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row = $row->toArray();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if($row){
            if($row['status'] == 2 || $row['status'] == 3){
                $row['time_end'] = date('Y-m-d H:i:s', $row['time_end']);
            }elseif ($row['status'] == 5){
                $row['refund_time'] = date('Y-m-d H:i:s', $row['refund_time']);

            }
            if($row['status'] != 2 || $row['status'] != 3){
                unset($row['transaction_id'], $row['time_end'], $row['total_fee']);
            }
            if($row['status'] != 5){
                unset($row['out_refund_no'], $row['refund_id'], $row['refund_time'], $row['refund_money']);
            }
            $row['use_status'] = \app\admin\model\Order::fetchUseStatus($row['use_status']);
            $row['status'] = \app\admin\model\Order::fetchStatus($row['status']);
            $row['pay_type'] = '微信支付';
            $row['createtime'] = date('Y-m-d H:i:s', $row['createtime']);

            if($row['venue_images']){
                $venue_images = explode(',', $row['venue_images']);
                $row['venue_images'] = $venue_images[0];
            }
            $time_list = json_decode($row['time_list'], true);
            $site_id_list = array_column($time_list, 'site_id');
            $site_list = \app\admin\model\Site::where('id', 'in', $site_id_list)->column('site_name', 'id');
            $time_data = "";
            foreach ($time_list as $key => $value){
                $time_data .= $site_list[$value['site_id']] . "：" . $value['time'] . "，";
            }
            $row['time_list'] = $time_data;

            unset($row['venue_id'],$row['user_id']);
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        $row                 = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->model->where('id', 'in', $ids)->update(['is_delete' => 2, 'deletetime' => time()]);
        $this->success();
    }

    /**
     * 退款
     */
    public function orderRefund($ids = "")
    {
        if (!$ids) {
            $this->error(__("Invalid parameters"));
        }
        $order = $this->model->field('id,user_id,out_trade_no,venue_id,date,time_list,all_money,status,use_status,createtime,time_end,out_refund_no,refund_time,pay_type,cancel_time')->where(['is_delete' => 1, 'id' => $ids])->find();
        if(!$order){
            $this->error('订单不存在');
        }
        $status_text = \app\admin\model\Order::fetchStatus($order['status']);
        if($order['status'] != 2){
            $this->error('订单' . $status_text);
        }
        $user = User::where(['id' => $order['user_id']])->find();
        //申请退款
        $update = ['status' => 5];
        $out_refund_no = $this->getOutRefundNo();
        $order['out_refund_no'] = $out_refund_no;
        $res = $this->refund($order, $user);
        if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
            $update['out_refund_no'] = $out_refund_no;
            $update['refund_id'] = $res['refund_id'];
            $update['refund_time'] = time();
            $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
            $result = $this->model->where('id', $ids)->update($update);
            //写入平台流水
            $platform_log = [
                'user_id' => $user['id'],
                'amount' => -$order['all_money'],
                'type' => 2,
                'log_note' => '订单退款',
                'order_id' => $order['id'],
                'createtime' => time(),
            ];
            \app\admin\model\PlatformLog::insert($platform_log);
            $this->success('退款成功');
        }else{
//            Db::name('log')->insert(['content' => json_encode($res, 256)]);
            $this->error($res['err_code_des']);
        }
    }

    //生成唯一退款号
    public function getOutRefundNo(){
        $out_refund_no = sys_create_orderno(4);
        $order = $this->model->where('out_refund_no', $out_refund_no)->count();
        if($order){
            $this->getOutRefundNo();
        }
        return $out_refund_no;
    }

    //退款
    public function refund($order, $user){
        $config = \think\facade\Config::get('config_wechat.wechat_pay');
        $app = Factory::payment($config);
        $result = $app->refund->byOutTradeNumber($order['out_trade_no'], $order['out_refund_no'], $order['all_money']*100, $order['all_money']*100, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '订单退款',
        ]);
        return $result;
    }

}
